package com.lintesis.lintesisview.common.converters;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

import javax.swing.text.NumberFormatter;

import org.zkoss.zk.ui.Component;
import org.zkoss.zkplus.databind.TypeConverter;

public class PercentageFormatConverter implements TypeConverter
{

	@Override
	public Object coerceToBean(Object arg0, Component comp)
	{
		if (arg0 == null)
		{
			return null;
		}
		NumberFormatter sdf = new NumberFormatter(NumberFormat.getPercentInstance(Locale.getDefault()));
		((DecimalFormat)sdf.getFormat()).setMaximumFractionDigits(2);
		try
		{
			return sdf.valueToString(arg0);
		} catch (ParseException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Object coerceToUi(Object arg0, Component comp)
	{
		if (arg0 == null || String.valueOf(arg0).length() == 0)
		{
			return null;
		}
		NumberFormatter sdf = new NumberFormatter(NumberFormat.getPercentInstance(Locale.getDefault()));
		((DecimalFormat)sdf.getFormat()).setMaximumFractionDigits(2);
		try
		{
			return sdf.valueToString(Double.valueOf(String.valueOf(arg0)));
		} catch (ParseException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static String getPattern()
	{
		DecimalFormat df=(DecimalFormat)NumberFormat.getPercentInstance(Locale.getDefault());
		df.setMaximumFractionDigits(2);
		return  df.toPattern();
	}
	
	public static void main (String args[])
	{
		Locale.setDefault(new Locale("es","PE"));
		System.out.println(getPattern());
	}
}
